import { storage } from "../utils"
import { Alert } from "../components"
import { types } from "mobx-state-tree"
// import { Api } from "../services/api/api"
import Fingerprint from "../vendor/scripts/fingerprint"
import http from "../services/api/apiLibrary"

export const RegisterStoreModel = types
  .model("RegisterStoreModel", {
    registerStep: 1,
    username: "",
    password: "",
    imgCode: "",
    uuid: new Fingerprint().get(),
    random: Math.random()
  })
  .views(self => ({}))
  .actions(self => ({
    imageChange() {
      self.uuid = new Fingerprint().get()
      self.random = Math.random()
    },

    usernameOnChange(text) {
      self.username = text
    },

    imgCodeOnChange(text) {
      self.imgCode = text
    },

    passwordOnChange(text) {
      self.password = text
    },

    nextStep() {
      self.registerStep = self.registerStep + 1
    },

    resetStep() {
      self.registerStep = 1
    },

    async setStorageValue(name, value) {
      await storage.save(name, value)
    },

    RegisterStep1() {
      const param = {
        username: self.username,
        imgCode: self.imgCode,
        uuid: self.uuid
      }
      http.post("/api/v2/register/exist/username", param).then(data => {
        const res = data.data
        if (res.code === 1) {
          self.nextStep()
        } else {
          Alert({
            title: "提示",
            message: res.message,
            text: "OK",
            onPress: () => console.log("OK Pressed")
          })
        }
      })
    },

    RegisterStep2(navigation, globalStore) {
      const param = {
        username: self.username,
        imgCode: self.imgCode,
        uuid: self.uuid,
        password: self.password
      }
      http.post("/api/v2/register/username", param).then(data => {
        const res = data.data
        if (res.code === 1) {
          self.setStorageValue("h5-token", res.data.token)
          globalStore.loginSuccess()
          navigation.navigate("Mine")
        } else {
          Alert({
            title: "提示",
            message: res.message,
            text: "OK",
            onPress: () => console.log("OK Pressed")
          })
        }
      })
    }
  }))
